import Taro, { Component } from "@tarojs/taro";
import { View, Text, RichText } from "@tarojs/components";
import { connect } from "@tarojs/redux";
import QR from 'wxmp-qrcode'
import {
  AtButton,
  AtActionSheet,
  AtCheckbox,
  AtModal,
  AtModalHeader,
  AtModalContent,
  AtModalAction,
  AtIcon,
  AtToast
} from "taro-ui";
import { $Req } from "@utils";
import BaseComponent from "@components/BaseComponent";
import "./index.scss";

const img_vip = 'https://bai-tong-fen-xiao.oss-cn-beijing.aliyuncs.com/imgs/vip/vip.png';
const wx_pay = 'https://bai-tong-fen-xiao.oss-cn-beijing.aliyuncs.com/imgs/vip/wx-pay.png';
const bank_card = 'https://bai-tong-fen-xiao.oss-cn-beijing.aliyuncs.com/imgs/vip/bank-card.png';
const qr_code = 'https://bai-tong-fen-xiao.oss-cn-beijing.aliyuncs.com/imgs/vip/qr-code.png';

@connect(
  ({ userModel }) => ({
    userModel,
  }),
  (dispatch) => ({
    userAction: dispatch.userModel,
  })
)
export default class Index extends Component {
  config = {
    navigationBarTitleText: "会员身份",
  };

  constructor(props) {
    super(...arguments);
    this.state = {
      rateVal: "2",
      productDetails: {},
      procotolData: {},
      modelOpen: false,
      showPayModel: false,
      payImg: "",
      isOk: [],
      // 显示提现方式
      showAction: false,
      checkboxOption: [
        {
          value: "0",
          name: "微信支付",
          icon: wx_pay,
          class: 'wx',
          is_checked: true,
        },
        {
          value: "1",
          name: "扫码支付",
          icon: qr_code,
          class: 'qr',
          is_checked: false,
        },
        {
          value: "2",
          name: "银行卡支付",
          icon: bank_card,
          class: 'bank',
          is_checked: false,
          bank_name: '中国建设银行',
          account: '账123456 7891234567'
        },
      ],
      aliPayOk: false,
      payMethodList: [],
      checkedPay: 1,
      admin_bank:{},
      ordersFlag: false,
    };
  }

  componentDidShow() {

    // 判断是否输入支付密码
    let payFlag = Taro.getStorageSync("syPay");
    if (payFlag) {
      this.buyOrder();
    }

    this.setState({
      productDetails: JSON.parse(this.$router.params.productDetails),
      modelOpen: false,
      checkedList: 0,
      showPayModel: false,
      aliPayOk: false,
    }, () => {
      console.log(this.state.productDetails, "---test--")
    });

    const {
      userModel: { userInfo }
    } = this.props;
    let shareId = this.$router.params.userId;
    console.log("获取到分享人的id：", shareId);

    if (!userInfo.userId) {
      userAction.setStatus({
        isOpen: true,
      });
      return;
    }

    if (shareId) {
      Taro.setStorageSync("shareId", shareId);
      if (userInfo.userId) {
        console.log("数据库有记录的，直接滚蛋。注册个jj");
        return false;
      }
    }
  }

  componentDidMount() {

    this.getSmallPayMode();

  }
  // 分享
  onShareAppMessage(res) {
    const {productDetails} = this.$router.params;
    const {
      userModel: { userInfo },
    } = this.props;
    return {
      title: '会员身份',
      path: `pages/vip/explain?productDetails=${productDetails}&userId=${userInfo.userId}`,
      imageUrl: "/images/aikepler-logo.jpeg",
      success: function (res) {
        // 转发成功
        console.log("转发成功");
      },
      fail: function (res) {
        // 转发失败
        console.log("转发失败");
      },
    };
  }

  // 点购买按钮
  onBtnClick(op) {
    const {
      userModel: { userInfo },
      userAction,
    } = this.props;

    // 整完加上
    if (!userInfo.userId) {
      userAction.setStatus({
        isOpen: true,
      });
      return;
    }

    this.getProcotol();
  }

  // 获取协议内容
  async getProcotol() {
    let { data } = await $Req({
      type: "get",
      url: "/distribution/getProtol",
      data: {},
    });

    this.setState({
      procotolData: data,
      modelOpen: true
    });
  }
  // 获取支付方式
  async getSmallPayMode() {
    let { data } = await $Req({
      type: 'get',
      url: '/order/getSmallPayMode',
      data: {},
    })
    if (!data) return;
    data.map((item)=> {
      if( item.payModeInt*1 == 6 ) {
          this.setState({
            admin_bank:item.platformBankCardVo  
          })
      }
    })
    this.setState({
      payMethodList: data
    })
  }
  // 查询支付结果
  async queryPay(orderId, checkoutId, amount) {
    let { data } = await $Req({
      type: "get",
      url: `/pay/queryPay`,
      data: {
        payModel: "MIC_DISTR_PAY_MODEL_NATIVE",
        payType: "MIC_DISTR_PAY_TYPE_ALIPAY",
        orderId,
        checkoutId,
        orderType: 2,
        amount
      }
    });
    if (!data) return;

    if (data.fundBillList && data.fundBillList.length) {
      this.setState({
        aliPayOk: true,
        showPayModel: false
      })
    }
  }

  async buyOrder() {
    const { checkedPay, productDetails } = this.state;
    let data = null;
    // 分销套餐包下订单
    if (productDetails.goodsType == 1) {

      /**
       * 套餐包的收益支付  开始
       * start
       * @returns
       * @memberof Index
       */ 
      if(checkedPay * 1 == 7) {
        let payFlag = Taro.getStorageSync("syPay");
        const {
          userModel: { userInfo },
        } = this.props;
  
        // 检查支付密码
        let abc = await $Req({
          type: "get",
          url: "/indexUser/checkHavePayPassword",
          data: { userId: userInfo.userId },
        });
  
        if (abc.code == 200) {
          if (!payFlag) {
            // 有密码
            if (abc.data) {
              Taro.navigateTo({
                url: `/pages/user/payPwd/index?flag=1&price=${productDetails.price}`
              })
              return false;
            }
            // 没密码 
            else {
              Taro.navigateTo({
                url: '/pages/user/payPwd/index'
              })
              return false;
            }
          } else {
            Taro.showLoading({
              title: "支付中..."
            })

            // this.syPay(currOrdersNo)
            var obj = await $Req({
              type: "post",
              url: "/distribution/addDistributionPackageOrder",
              data: {
                payType: 8,
                distributionGoodsId: productDetails.id,
              },
            });
            Taro.removeStorageSync("syPay");
            if (!obj.data) return;
            
            Taro.hideLoading();
            
            Taro.showToast({
              title: "支付成功",
              icon: "none"
            })

            this.setState({
              showAction: false,
            })

            return false;
          }
        }
      } else {
        var res = await $Req({
          type: "post",
          url: "/distribution/addDistributionPackageOrder",
          data: {
            payType: checkedPay == 7 ? 8 : checkedPay,
            distributionGoodsId: productDetails.id,
          },
        });
        console.log(res, "--- data ---");
        if (!res.data) return;
        
  
        data = res.data;
      }

      /**
       * 套餐包的收益支付  结束
       * start
       * @returns
       * @memberof Index
       */

    } else { // 分销商下订单 

      /**
       * 该判断是分销商的收益支付  开始
       * start
       * @returns
       * @memberof Index
       */ 
      if(checkedPay * 1 == 7) {
        let payFlag = Taro.getStorageSync("syPay");
        const {
          userModel: { userInfo },
        } = this.props;
  
        // 检查支付密码
        let abc = await $Req({
          type: "get",
          url: "/indexUser/checkHavePayPassword",
          data: { userId: userInfo.userId },
        });
  
        if (abc.code == 200) {
          if (!payFlag) {
            // 有密码
            if (abc.data) {
              Taro.navigateTo({
                url: `/pages/user/payPwd/index?flag=1&price=${productDetails.price}`
              })
              return false;
            }
            // 没密码 
            else {
              Taro.navigateTo({
                url: '/pages/user/payPwd/index'
              })
              return false;
            }
          } else {
            Taro.showLoading({
              title: "支付中..."
            })

            var res = await $Req({
              type: "post",
              url: "/distribution/addDistributionOrder",
              data: {
                payType: checkedPay == 7 ? 8 : checkedPay,
                distributionGoodsId: productDetails.id,
              },
            });
            Taro.removeStorageSync("syPay");
            if (!res.data) return;
            
            Taro.hideLoading();
            
            Taro.showToast({
              title: "支付成功",
              icon: "none"
            })

            this.setState({
              showAction: false,
            })

            return false;
          }
        }
      } else {
        var res = await $Req({
          type: "post",
          url: "/distribution/addDistributionOrder",
          data: {
            payType: checkedPay == 7 ? 8 : checkedPay,
            distributionGoodsId: productDetails.id,
          },
        });
        console.log(res, "--- data ---");
        if (!res.data) return;
        
  
        data = res.data;
      }

      /**
       * 该判断是分销商的收益支付  结束
       * end
       * @returns
       * @memberof Index
       */ 
    }
    
    if (checkedPay * 1 == 1) {
      this.getPaySign(data.id);
    } else if (checkedPay * 1 == 2) {
      // 支付宝支付
      this.getNativePaySign(data.id);
    } else if(checkedPay * 1 == 5) {
      this.setState({
        hintFlag: true,
        hintTxt: '支付成功，后台审核中'
      });
    }

    this.setState({
      showAction: false,
      ordersFlag: checkedPay * 1 == 6
    })
  }

  // 收益支付
  // async syPay(ordersNo) {
  //   let { code, message } = await $Req({
  //     type: "post",
  //     url: `/order/usebenefitPay?ordersNo=${ordersNo}`
  //   });
  //   if (code == 200) {
  //     console.log("支付成功！");
  //   } else {
  //     Taro.showToast({
  //       title: message,
  //       icon: "none"
  //     })
  //   }
    
  //   Taro.removeStorageSync("syPay");
  //   Taro.removeStorageSync("ordersNo");

  // }


  // 支付宝支付签名
  async getNativePaySign(orderId) {

    const {
      userModel: { userInfo },
    } = this.props;
    let { data } = await $Req({
      type: "post",
      url: `/pay/pay?userId=${userInfo.userId}&orderId=${orderId}&amount=${this.state.productDetails.price * 100}&orderType=${2}&payModel=MIC_DISTR_PAY_MODEL_NATIVE&payType=MIC_DISTR_PAY_TYPE_ALIPAY`,
    });
    if (!data) return;

    this.setState({
      showPayModel: true
    }, () => {
      QR.draw(data.qrCode, "canvas")

      let Timer = setInterval(() => {
        if (this.state.aliPayOk) {
          clearInterval(Timer);

          Taro.redirectTo({
            url: "/pages/vip/success?productDetails=" + JSON.stringify(this.state.productDetails),
          });
        } else {
          this.queryPay(orderId, data.checkoutId, this.state.productDetails.price * 100);
        }
      }, 2000)
    })


  }

  // 获取支付签名
  async getPaySign(orderId) {
    const {
      userModel: { userInfo },
    } = this.props;
    let { code, message, data } = await $Req({
      type: "post",
      url: `/pay/pay?userId=${userInfo.userId}&openId=${userInfo.openId}&orderId=${orderId}&amount=${this.state.productDetails.price * 100}&orderType=${2}&payModel=MIC_DISTR_PAY_MODEL_MINI_APP&payType=MIC_DISTR_PAY_TYPE_WEBCHAT`,
    });
    if (!data) return;
    this.payOrder(data);
  }

  // 微信支付
  payOrder(res) {
    let _this = this;
    Taro.requestPayment({
      timeStamp: res.timeStamp,
      nonceStr: res.nonceStr,
      signType: "MD5",
      package: res.package,
      paySign: res.paySign,
      success(res) {
        Taro.redirectTo({
          url: "/pages/vip/success?productDetails=" + JSON.stringify(_this.state.productDetails),
        });
      },
      fail(res) {
        Taro.showToast({
          title: "支付失败",
          icon: "none",
          duration: 1000,
        });
      },
    });
  }

  checkedHandle(e) {
    const dataset = e.currentTarget.dataset;
    console.log(dataset)
    this.setState({
      checkedPay: dataset.val
    });

  }

  render() {
    const { payMethodList, checkedPay, hintFlag, hintTxt } = this.state;
    return (
      <BaseComponent>
        <View className="at-row page-user-explain">
          <View className="at-col">
            <View className="at-row">
              <View className="at-col">
                <image
                  style="width:100%;height:168PX;"
                  src={
                    "https://bai-tong-fen-xiao.oss-cn-beijing.aliyuncs.com" +
                    "/shopping/user/welfare.png"
                  }
                />
              </View>
            </View>
            <View className="at-row at-row__align--center">
              <View className="at-col at-col-2" style="padding-left:12PX;">
                <view class="color-box">
                  <image src={img_vip} />
                </view>
              </View>
              <View
                className="at-col at-col-6 left"
                style="padding:15PX;padding-left:0;"
              >
                <View className="at-row at-row__align--center">
                  <View className="at-col">
                    <Text className="name">
                      {productDetails.distributionName}
                    </Text>
                  </View>
                </View>
                <View className="at-row at-row__align--center">
                  <View className="at-col">
                    <Text style="color: #DF1616;font-size: 14PX;">
                      ￥{productDetails.price}
                    </Text>
                  </View>
                </View>
              </View>
              <View className="at-col at-col-4 right" style="padding:15PX">
                <Button class="share-btn" open-type="share">分享</Button>
              </View>
            </View>

            <View className="at-row" style="min-height:150PX;">
              <View className="at-col" style="white-space: initial !important;">
                <View className="at-article">
                  <View style="padding: 0 20px;" className="rich">
                    <RichText nodes={productDetails.des} />
                  </View>
                </View>
              </View>
            </View>
          </View>

          <AtModal
            id="chnages"
            isOpened={this.state.modelOpen}
            onClose={() => {
              this.setState({
                modelOpen: false,
              });
            }}
          >
            <AtModalHeader>分销协议</AtModalHeader>
            <AtModalContent>
              <RichText className="text" nodes={this.state.procotolData.procotolContent} />
              <AtCheckbox
                options={[
                  {
                    value: "isTrue",
                    label: "我已阅读并同意《分销商入驻协议》",
                  },
                ]}
                selectedList={this.state.isOk}
                onChange={(val) => {
                  this.setState({
                    isOk: val,
                  });
                }}
              />
            </AtModalContent>
            <AtModalAction>
              <Button
                onClick={() => {
                  this.setState({
                    modelOpen: false,
                  });
                }}
              >
                取消
              </Button>
              <Button
                onClick={() => {
                  if (this.state.isOk.length) {
                    this.setState({
                      modelOpen: false,
                    });
                    if( payMethodList.length == 0 ) {
                      this.buyOrder();    
                    } else{
                      this.setState({ 
                        showAction: true
                      });
                    }
                  } else {
                    Taro.showToast({
                      title: "请勾选已阅读在进行下一步操作",
                      icon: "none",
                    });
                  }
                }}
              >
                确定
              </Button>
            </AtModalAction>
          </AtModal>
          <AtActionSheet isOpened={this.state.showAction} title="选择支付方式" onClose={
            () => {
              this.setState({
                showAction: false
              })
            }
          }>

            <AtActionSheetItem>
              {
                payMethodList.map((item, index) => (
                  <View>
                    <View className='at-row pay-mode' data-val={item.payModeInt} style={{ borderBottom: item.payModeInt == 6 ? '0PX' : '1PX solid #F1F1F1' }} onClick={this.checkedHandle.bind(this)} key={item.payModeInt} >
                      <View className='at-col item-left'>
                        {item.payPngUrl?
                          <View style="display:flex;align-items: center;"><Image mode="widthFix" style="width:16PX;height:16PX;margin-right:4PX;" src={item.payPngUrl} ></Image>{item.payModeName}</View>
                         : <View style="padding-left:19PX;">{item.payModeName}</View>
                        }
                      </View>
                      <View className='at-col item-right' style={{ backgroundColor: checkedPay == item.payModeInt ? '#17A8E6' : '#fff' }}>
                        <AtIcon value='check' size='13' color='#FFF'></AtIcon>
                      </View>
                    </View>
                    {(item.payModeInt == 6 && checkedPay == 6) ? (
                      <View class='bank-info' onClick={() => {
                        Taro.setClipboardData({
                          data: `姓名:${item.platformBankCardVo.bankUserName};开户行:${item.platformBankCardVo.bankName};账号:${item.platformBankCardVo.bankNum};`,
                          success (res) {
                          }
                        })
                      }}>
                        <View>姓名：{item.platformBankCardVo.bankUserName}</View>
                        <View>开户行：{item.platformBankCardVo.bankName}</View>
                        <View>账号：{item.platformBankCardVo.bankNum}</View>
                      </View>
                    ) : null}
                  </View>
                ))
              }
              <View style="padding:24PX 19PX;">
                <AtButton circle type="primary" onClick={() => { this.buyOrder(); }}>确定</AtButton>
              </View>

            </AtActionSheetItem>
            {/* <AtCheckbox
              options={this.state.checkboxOption}
              selectedList={[this.state.checkedList]}
              onChange={(v, op) => {
                console.log(v);
                this.setState({
                  checkedList: v[1]
                }, () => {
                  this.buyOrder();
                })
              }}
            /> */}
          </AtActionSheet>
        </View>

        <View style="padding:30PX 16PX;">
          <AtButton
            circle
            type="primary"
            onClick={() => {
              this.onBtnClick();
            }}
          >
            立即购买
        </AtButton>
        </View>
        {/* 支付宝支付 */}
        <AtModal isOpened={this.state.showPayModel} onClose={
          () => {
            this.setState({
              showPayModel: false
            })
          }
        }
        >
          <AtModalHeader>扫码支付</AtModalHeader>
          <AtModalContent>
            {
              this.state.showPayModel ?
                <canvas style="margin-left: -24px;" id="canvas" canvas-id="canvas"></canvas>
                :
                null
            }
          </AtModalContent>
          <AtModalAction><Button onClick={
            () => {
              this.setState({
                showPayModel: false
              })
            }
          }>确定</Button></AtModalAction>
        </AtModal>
        {/* 银行卡下单 */}
        <AtModal isOpened={this.state.ordersFlag}>
          <AtModalHeader>下单成功</AtModalHeader>
          <AtModalContent className="orders-info">
            <View onClick={() => {
              Taro.setClipboardData({
                data: `姓名:${admin_bank.bankUserName};开户行:${admin_bank.bankName};账号:${admin_bank.bankNum};`,
                success (res) {
                }
              })
            }}>
              <View>平台收款账号</View>
              <View>姓名: {admin_bank.bankUserName}</View>
              <View>开户行: {admin_bank.bankName}</View>
              <View>账号: {admin_bank.bankNum}</View>
              <View className="hint">银行转账给收款账号，转账后联系平台核对款项</View>
            </View>
          </AtModalContent>
          <AtModalAction><Button onClick={() => {
            this.setState({
              ordersFlag: false
            })
           }}>确定</Button> </AtModalAction>
        </AtModal>
        <AtToast isOpened={hintFlag} text={hintTxt} onClose={()=>{
          this.setState({
            hintFlag: false
          })
        }}></AtToast>
      </BaseComponent>
    );
  }
}
